package com.viaas.certification.image;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class HttpPostRequest {
    public static String post(String message){
        String apiUrl = "http://localhost:5000/chat"; // 你的 API 地址
        String authToken = "Bearer sk-866439667fcb4a60b5cca6af14959d7d"; // 你的 Token

        String jsonInputString = String.format("{ \"message\": \"%s\" }", message);

        try {
            // 创建 URL 连接
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 配置请求方法和 Header
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            conn.setRequestProperty("Authorization", authToken);
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0");

            // 启用输出流
            conn.setDoOutput(true);

            // 发送 JSON 数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = conn.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8);
                String responseBody = scanner.useDelimiter("\\A").next();
                scanner.close();
                // 使用 Gson 解析 JSON 字符串
                JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject();
                String decodedResponse = jsonObject.get("response").getAsString();
                return decodedResponse;
            } else {
                System.out.println("Error: " + responseCode);
            }

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
